import tkinter as tk
from tkinter import ttk, messagebox
from GUI界面.BaseSubWindow import BaseSubWindow
from 数据库操作.GetBlogList import GetBlogList
from 数据库操作.CommentOperation import CommentOperation
from 数据库操作.FollowOperation import FollowOperation
from 数据库操作.CreateMysqlCon import CreateMysqlCon


class BlogList(BaseSubWindow):
    """
    博客列表界面
    """
    def create_widgets(self):
        # 创建标签页控件
        self.notebook = ttk.Notebook(self)
        self.notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 创建所有博客页面
        self.all_blogs_frame = ttk.Frame(self.notebook)
        self.notebook.add(self.all_blogs_frame, text="所有博客")
        
        # 创建关注博客页面
        self.followed_blogs_frame = ttk.Frame(self.notebook)
        self.notebook.add(self.followed_blogs_frame, text="关注的博客")
        
        # 初始化所有博客页面
        self.init_all_blogs_page()
        
        # 初始化关注博客页面
        self.init_followed_blogs_page()
        
        # 绑定标签页切换事件
        self.notebook.bind("<<NotebookTabChanged>>", self.on_tab_changed)
        
    def init_all_blogs_page(self):
        """初始化所有博客页面"""
        # 创建带滚动条的树形视图框架
        tree_frame = ttk.Frame(self.all_blogs_frame)
        tree_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建滚动条
        scrollbar = ttk.Scrollbar(tree_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 创建树形视图
        self.all_blogs_tree = ttk.Treeview(tree_frame, 
                                         columns=("id", "title", "username", "content", "time"), 
                                         show="headings",
                                         yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.all_blogs_tree.yview)
        
        # 配置列
        self.all_blogs_tree.column("id", width=50)
        self.all_blogs_tree.column("title", width=150)
        self.all_blogs_tree.column("username", width=100)
        self.all_blogs_tree.column("content", width=300)
        self.all_blogs_tree.column("time", width=150)
        
        # 设置列标题
        self.all_blogs_tree.heading("id", text="ID")
        self.all_blogs_tree.heading("title", text="标题")
        self.all_blogs_tree.heading("username", text="作者")
        self.all_blogs_tree.heading("content", text="内容")
        self.all_blogs_tree.heading("time", text="发表时间")
        
        # 填充数据
        self.refresh_all_blogs()
        
        self.all_blogs_tree.pack(fill=tk.BOTH, expand=True)
        
        # 绑定点击事件
        self.all_blogs_tree.bind("<Double-1>", self.show_all_blog_details)  # 双击打开详情窗口
        
        # 刷新按钮
        refresh_button = ttk.Button(self.all_blogs_frame, text="刷新列表", command=self.refresh_all_blogs)
        refresh_button.pack(pady=10)
        
    def init_followed_blogs_page(self):
        """初始化关注博客页面"""
        # 创建带滚动条的树形视图框架
        tree_frame = ttk.Frame(self.followed_blogs_frame)
        tree_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建滚动条
        scrollbar = ttk.Scrollbar(tree_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 创建树形视图
        self.followed_blogs_tree = ttk.Treeview(tree_frame, 
                                              columns=("id", "title", "username", "content", "time"), 
                                              show="headings",
                                              yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.followed_blogs_tree.yview)
        
        # 配置列
        self.followed_blogs_tree.column("id", width=50)
        self.followed_blogs_tree.column("title", width=150)
        self.followed_blogs_tree.column("username", width=100)
        self.followed_blogs_tree.column("content", width=300)
        self.followed_blogs_tree.column("time", width=150)
        
        # 设置列标题
        self.followed_blogs_tree.heading("id", text="ID")
        self.followed_blogs_tree.heading("title", text="标题")
        self.followed_blogs_tree.heading("username", text="作者")
        self.followed_blogs_tree.heading("content", text="内容")
        self.followed_blogs_tree.heading("time", text="发表时间")
        
        # 填充数据
        self.refresh_followed_blogs()
        
        self.followed_blogs_tree.pack(fill=tk.BOTH, expand=True)
        
        # 绑定点击事件
        self.followed_blogs_tree.bind("<Double-1>", self.show_followed_blog_details)  # 双击打开详情窗口
        
        # 刷新按钮
        refresh_button = ttk.Button(self.followed_blogs_frame, text="刷新列表", command=self.refresh_followed_blogs)
        refresh_button.pack(pady=10)
        
    def on_tab_changed(self, event):
        """标签页切换事件"""
        current_tab = self.notebook.index(self.notebook.select())
        if current_tab == 0:  # 所有博客页面
            self.refresh_all_blogs()
        elif current_tab == 1:  # 关注博客页面
            self.refresh_followed_blogs()
            
    def refresh_all_blogs(self):
        """刷新所有博客列表"""
        # 清空现有数据
        for item in self.all_blogs_tree.get_children():
            self.all_blogs_tree.delete(item)
            
        # 获取并显示数据
        result = GetBlogList().get_blog_list()
        for row in result:
            self.all_blogs_tree.insert("", "end", values=row)
            
    def refresh_followed_blogs(self):
        """刷新关注博客列表"""
        # 清空现有数据
        for item in self.followed_blogs_tree.get_children():
            self.followed_blogs_tree.delete(item)
            
        try:
            # 获取用户ID
            cursor = CreateMysqlCon().get_con().cursor()
            cursor.execute("SELECT ID FROM user_data WHERE username = %s", (self.user.username,))
            user_id = cursor.fetchone()
            
            if user_id:
                # 获取并显示数据
                result = FollowOperation().get_followed_blogs(user_id[0])
                for row in result:
                    self.followed_blogs_tree.insert("", "end", values=row)
        except Exception as e:
            print(f"刷新关注博客列表失败: {e}")

    def show_all_blog_details(self, event):
        """显示所有博客页面中的博客详情"""
        self.show_blog_details(event, self.all_blogs_tree)
        
    def show_followed_blog_details(self, event):
        """显示关注博客页面中的博客详情"""
        self.show_blog_details(event, self.followed_blogs_tree)
        
    def show_blog_details(self, event, tree):
        """显示博客详情"""
        try:
            selected_item = tree.selection()[0]  # 获取选中项
            blog_data = tree.item(selected_item, "values")  # 获取值（元组）
            blog_id = blog_data[0]
            blog_title = blog_data[1]
            blog_author = blog_data[2]
            blog_content = blog_data[3]
            
            # 创建新窗口显示详细信息
            detail_window = tk.Toplevel(self)
            detail_window.title(blog_title)  # 标题作为窗口标题
            detail_window.geometry("600x500")
            
            # 创建标题和作者标签
            title_frame = ttk.Frame(detail_window)
            title_frame.pack(fill=tk.X, padx=10, pady=10)
            
            title_label = ttk.Label(title_frame, text=f"标题: {blog_title}", font=("Arial", 14))
            title_label.pack(side=tk.LEFT, pady=5)
            
            # 获取当前用户ID
            cursor = CreateMysqlCon().get_con().cursor()
            cursor.execute("SELECT ID FROM user_data WHERE username = %s", (self.user.username,))
            current_user_id = cursor.fetchone()[0]
            
            # 获取博客作者ID
            cursor.execute("SELECT ID FROM user_data WHERE username = %s", (blog_author,))
            author_id = cursor.fetchone()[0]
            
            # 不能关注自己
            if current_user_id != author_id:
                # 检查是否已关注
                is_following = FollowOperation().is_following(current_user_id, author_id)
                
                # 创建关注/取消关注按钮
                if is_following:
                    follow_button = ttk.Button(
                        title_frame, 
                        text="取消关注", 
                        command=lambda: self.toggle_follow(author_id, blog_author, False, detail_window)
                    )
                else:
                    follow_button = ttk.Button(
                        title_frame, 
                        text="关注作者", 
                        command=lambda: self.toggle_follow(author_id, blog_author, True, detail_window)
                    )
                follow_button.pack(side=tk.RIGHT, padx=5)
            
            author_label = ttk.Label(detail_window, text=f"作者: {blog_author}")
            author_label.pack(anchor="w", padx=10)
            
            # 创建内容文本框
            content_frame = ttk.LabelFrame(detail_window, text="博客内容")
            content_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
            
            content_text = tk.Text(content_frame, wrap="word", height=10)
            content_text.insert(tk.END, blog_content)
            content_text.config(state=tk.DISABLED)  # 设置为只读
            content_text.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)
            
            # 创建评论区
            comment_frame = ttk.LabelFrame(detail_window, text="评论区")
            comment_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)
            
            # 创建评论列表的滚动区域
            comment_canvas = tk.Canvas(comment_frame)
            comment_scrollbar = ttk.Scrollbar(comment_frame, orient="vertical", command=comment_canvas.yview)
            comment_scrollable_frame = ttk.Frame(comment_canvas)
            
            comment_scrollable_frame.bind(
                "<Configure>",
                lambda e: comment_canvas.configure(scrollregion=comment_canvas.bbox("all"))
            )
            
            comment_canvas.create_window((0, 0), window=comment_scrollable_frame, anchor="nw")
            comment_canvas.configure(yscrollcommand=comment_scrollbar.set)
            
            comment_canvas.pack(side="left", fill="both", expand=True, padx=5, pady=5)
            comment_scrollbar.pack(side="right", fill="y", pady=5)
            
            # 评论列表
            comments = CommentOperation().get_comments_by_blog(blog_id)
            if comments:
                for comment in comments:
                    comment_frame = ttk.Frame(comment_scrollable_frame)
                    comment_frame.pack(fill=tk.X, padx=5, pady=2)
                    
                    comment_text = f"{comment[1]} ({comment[3].strftime('%Y-%m-%d %H:%M')}): {comment[2]}"
                    comment_label = ttk.Label(comment_frame, text=comment_text, wraplength=500)
                    comment_label.pack(side=tk.LEFT, anchor="w")
                    
                    # 如果是自己的评论，添加删除按钮
                    if comment[1] == self.user.username:
                        delete_button = ttk.Button(
                            comment_frame, 
                            text="删除", 
                            width=5,
                            command=lambda cid=comment[0]: self.delete_comment(cid, blog_id, detail_window)
                        )
                        delete_button.pack(side=tk.RIGHT)
            else:
                ttk.Label(comment_scrollable_frame, text="暂无评论").pack(padx=5, pady=10)
            
            # 添加评论输入框
            input_frame = ttk.Frame(detail_window)
            input_frame.pack(padx=10, pady=10, fill=tk.X)
            
            comment_entry = ttk.Entry(input_frame, width=50)
            comment_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)
            
            # 添加评论按钮
            def add_comment():
                content = comment_entry.get().strip()
                if not content:
                    messagebox.showwarning("警告", "评论内容不能为空")
                    return
                    
                # 添加评论
                if CommentOperation().add_comment(blog_id, current_user_id, content):
                    messagebox.showinfo("成功", "评论已添加")
                    detail_window.destroy()  # 关闭当前窗口
                    self.show_blog_details(event, tree)  # 重新打开详情窗口以刷新评论
                else:
                    messagebox.showerror("错误", "评论添加失败")
            
            comment_button = ttk.Button(input_frame, text="发表评论", command=add_comment)
            comment_button.pack(side=tk.RIGHT, padx=5)
        except Exception as e:
            messagebox.showerror("错误", f"显示博客详情失败: {e}")
            print(f"显示博客详情失败: {e}")
            
    def toggle_follow(self, author_id, author_name, is_follow, detail_window):
        """关注或取消关注作者"""
        try:
            # 获取当前用户ID
            cursor = CreateMysqlCon().get_con().cursor()
            cursor.execute("SELECT ID FROM user_data WHERE username = %s", (self.user.username,))
            current_user_id = cursor.fetchone()[0]
            
            follow_op = FollowOperation()
            if is_follow:
                # 关注作者
                if follow_op.follow_user(current_user_id, author_id):
                    messagebox.showinfo("成功", f"已关注 {author_name}")
                    # 刷新窗口
                    detail_window.destroy()
                    # 刷新关注博客列表
                    self.refresh_followed_blogs()
                else:
                    messagebox.showerror("错误", f"关注 {author_name} 失败")
            else:
                # 取消关注
                if follow_op.unfollow_user(current_user_id, author_id):
                    messagebox.showinfo("成功", f"已取消关注 {author_name}")
                    # 刷新窗口
                    detail_window.destroy()
                    # 刷新关注博客列表
                    self.refresh_followed_blogs()
                else:
                    messagebox.showerror("错误", f"取消关注 {author_name} 失败")
        except Exception as e:
            messagebox.showerror("错误", f"操作失败: {e}")
            print(f"关注/取消关注失败: {e}")
            
    def delete_comment(self, comment_id, blog_id, detail_window):
        """删除评论"""
        try:
            # 获取当前用户ID
            cursor = CreateMysqlCon().get_con().cursor()
            cursor.execute("SELECT ID FROM user_data WHERE username = %s", (self.user.username,))
            current_user_id = cursor.fetchone()[0]
            
            # 删除评论
            if CommentOperation().delete_comment(comment_id, current_user_id):
                messagebox.showinfo("成功", "评论已删除")
                # 刷新窗口
                detail_window.destroy()
            else:
                messagebox.showerror("错误", "删除评论失败，可能不是您的评论")
        except Exception as e:
            messagebox.showerror("错误", f"删除评论失败: {e}")
            print(f"删除评论失败: {e}")


